import {
  DatePicker,
  Form,
  Input,
  Select,
  Button,
  message,
  Steps,
  theme,
  Upload,
  Modal
} from "antd";
import React, { useState } from "react";
import { UploadOutlined } from "@ant-design/icons";


const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  },
};

const { Option } = Select;

const provinceDate = [
  { id: 1, province: "河北" },
  { id: 2, province: "山西" },
  { id: 3, province: "辽宁" },
  { id: 4, province: "吉林" },
  { id: 5, province: "黑龙江" },
  { id: 6, province: "江苏" },
  { id: 7, province: "浙江" },
  { id: 8, province: "安徽" },
  { id: 9, province: "福建" },
  { id: 10, province: "江西" },
  { id: 11, province: "山东" },
  { id: 12, province: "河南" },
  { id: 13, province: "湖北" },
  { id: 14, province: "湖南" },
  { id: 15, province: "广东" },
  { id: 16, province: "海南" },
  { id: 17, province: "四川" },
  { id: 18, province: "贵州" },
  { id: 19, province: "云南" },
  { id: 20, province: "陕西" },
  { id: 21, province: "甘肃" },
  { id: 22, province: "青海" },
  { id: 23, province: "台湾" },
  { id: 24, province: "内蒙古" },
  { id: 25, province: "广西" },
  { id: 26, province: "西藏" },
  { id: 27, province: "宁夏" },
  { id: 28, province: "新疆" },
  { id: 29, province: "北京" },
  { id: 30, province: "天津" },
  { id: 31, province: "上海" },
  { id: 32, province: "重庆" },
  { id: 33, province: "香港" },
  { id: 34, province: "澳门" },
];

const payDate = [
  { id: 1, way: "纯积分" },
  { id: 2, way: "积分+现金" },
  { id: 3, way: "现金购买" },
];

const parentCategoryDate=[
  {id:112000,parentCategory:"个人护理"},
  {id:113000,parentCategory:"纸品家清"},
  {id:111000,parentCategory:"母婴用品"},
  {id:110000,parentCategory:"医疗保健"},
  {id:115000,parentCategory:"美容护肤"},
  {id:116000,parentCategory:"宠物生活"},
  {id:107000,parentCategory:"粮油调味"},
  {id:109000,parentCategory:"日用百货"},
  {id:117000,parentCategory:"品质生鲜"},
  {id:114000,parentCategory:"电器数码"},
  {id:108000,parentCategory:"乳饮酒水"},
  {id:103000,parentCategory:"甄选美食"},

];

const childCategoryDate=[
   { id: 112007, parentId: 112000, childCategory: "身体护理" },
   { id: 111010, parentId: 111000, childCategory: "宝宝奶粉" },
   { id: 112001, parentId: 112000, childCategory: "洗发护发" },
   { id: 112002, parentId: 112000, childCategory: "淋浴用品" },
   { id: 112003, parentId: 112000, childCategory: "牙膏牙刷" },
   { id: 112004, parentId: 112000, childCategory: "脸部护理" },
   { id: 112005, parentId: 112000, childCategory: "烫发染发" },
   { id: 112006, parentId: 112000, childCategory: "洗手护手" },
   { id: 111009, parentId: 111000, childCategory: "童鞋童装" },
   { id: 112008, parentId: 112000, childCategory: "足部护理" },
   { id: 113001, parentId: 113000, childCategory: "抽纸卷纸" },
   { id: 113002, parentId: 113000, childCategory: "湿巾清洁" },
   { id: 113003, parentId: 113000, childCategory: "精致洗衣" },
   { id: 113004, parentId: 113000, childCategory: "衣物护理" }, 
   { id: 113005, parentId: 113000, childCategory: "厨卫清洁" },
   { id: 113006, parentId: 113000, childCategory: "除菌消毒" },
   { id: 109009, parentId: 109000, childCategory: "生活日用" },
   { id: 110001, parentId: 110000, childCategory: "保健食品" },
   { id: 110002, parentId: 110000, childCategory: "传统滋补" },
   { id: 110002, parentId: 110000, childCategory: "传统滋补" },
   { id: 110003, parentId: 110000, childCategory: "家庭护理" },
   { id: 110004, parentId: 110000, childCategory: "宝妈必备" },
   { id: 110005, parentId: 110000, childCategory: "瘦身健体" },
   { id: 110006, parentId: 110000, childCategory: "医疗防护" },
   { id: 113007, parentId: 113000, childCategory: "清洁工具" },
   { id: 111001, parentId: 111000, childCategory: "洗护用品" },
   { id: 111002, parentId: 111000, childCategory: "奶瓶餐具" },
   { id: 111004, parentId: 111000, childCategory: "宝宝尿裤" },
   { id: 111005, parentId: 111000, childCategory: "辅食零食" },
   { id: 111006, parentId: 111000, childCategory: "潮流玩具" },
   { id: 111007,  parentId:111000, childCategory: "孕妈护理" },
   { id: 111008,  parentId:111000, childCategory: "童书书籍" },
   { id: 117005,  parentId:117000, childCategory: "绿植鲜花" },
   { id: 116002,  parentId:116000, childCategory: "猫狗衣物" },
   { id: 116003,  parentId:116000, childCategory: "猫狗玩具" },
   { id: 116004,  parentId:116000, childCategory: "猫狗清洁" },
   { id: 117001,  parentId:117000, childCategory: "猪牛羊肉" }, 
   { id: 117002,  parentId:117000, childCategory: "禽肉蛋品" },
   { id: 117003,  parentId:117000, childCategory: "海鲜水产" }, 
   { id: 117004,  parentId:117000, childCategory: "速冻食品" },
   { id: 116001,  parentId:116000, childCategory: "猫粮狗粮" },
   { id: 117006,  parentId:117000, childCategory: "水果蔬菜" },
   { id: 109010,  parentId:109000, childCategory: "精品鞋袜" },
   { id: 109011,  parentId:109000, childCategory: "箱包皮具" }, 
   { id: 109012,  parentId:109000, childCategory: "钟表珠宝" },
   { id: 114007,  parentId:114000, childCategory: "手机周边" },
   { id: 114002,  parentId:114000, childCategory: "厨房电器" },
   { id: 114004,  parentId:114000, childCategory: "居家清洁" },
   { id: 114005,  parentId:114000, childCategory: "按摩器材" },
   { id: 109008,  parentId:109000, childCategory: "一次性用品"},
   { id: 115001,  parentId:115000, childCategory: "秋冬护理"},  
   { id: 115002,  parentId:115000, childCategory: "亮颜美白"},
   { id: 115003,  parentId:115000, childCategory: "面膜卸妆"},
   { id: 115004,  parentId:115000, childCategory: "防晒必备"},
   { id: 115006,  parentId:115000, childCategory: "唇眉眼妆"},
   { id: 103012,  parentId:103000, childCategory: "鱼干海苔"},
   { id: 107004,  parentId:107000, childCategory: "面粉面条"},
   { id: 107003,  parentId:107000, childCategory: "厨房调味"},
   { id: 107002,  parentId:107000, childCategory: "精选粮油"},
   { id: 107006,  parentId:107000, childCategory: "调味酱料"},
   { id: 107001,  parentId:107000, childCategory: "优质大米"},
   { id: 103015,  parentId:103000, childCategory: "糖果巧克力"},
   { id: 103014,  parentId:103000, childCategory: "儿童零食"},
   { id: 103013,  parentId:103000, childCategory: "营养早餐"},
   { id: 103011,  parentId:103000, childCategory: "肉干辣条"},
   { id: 103010,  parentId:103000, childCategory: "薯片膨化"},
   { id: 103007,  parentId:103000, childCategory: "面包蛋糕"},
   { id: 108001,  parentId:108000, childCategory: "牛奶奶粉"},
   { id: 108005,  parentId:108000, childCategory: "白酒黄酒"},
   { id: 108002,  parentId:108000, childCategory: "咖啡麦片"},
   { id: 108003,  parentId:108000, childCategory: "红酒啤酒"},
   { id: 108004,  parentId:108000, childCategory: "美味果酒"},           
]
 

const provinceOption = provinceDate.map((provinceDate) => (
  <Option key={provinceDate.id}>{provinceDate.province}</Option>
));


const payOption = payDate.map((payDate) => (
  <Option key={payDate.id}>{payDate.way}</Option>
));

const parentCategoryOption = parentCategoryDate.map((parentCategoryDate) => (
  <Option key={parentCategoryDate.id} value={parentCategoryDate.id}>{parentCategoryDate.parentCategory}</Option>
));

const childCategoryOption = (parentId:number) => {
  const filteredOption = childCategoryDate.filter(
    (childCategoryDate) => childCategoryDate.parentId === parentId
  );
  return filteredOption.map((category) => (
    <Option key={category.id} value={category.childCategory}>
      {category.childCategory}
    </Option>
  ));
};


function AddProduct() {
  const [form] = Form.useForm();
  const [parentId, setParentId] = useState(-1);
  const [fileList, setFileList] = useState([]);

 const [priceRows, setPriceRows] = useState([
    { id: 1, payType: undefined, pointPrice: undefined, cashPrice: undefined },
  ]);

  // 预览图片
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  Modal.info({
    title: file.name,
    content: (
      <img src={file.url || file.preview} style={{ width: "100%" }} />
    ),
    onOk() {},
  });
};

// 删除图片
const handleRemove = (file) => {
  setFileList((prevList) => prevList.filter((item) => item.uid !== file.uid));
};

// 将图片转换为base64格式
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

  const handleAddRow = () => {
  const newRow = {
    id: priceRows.length + 1,
    payType: undefined,
    pointPrice: undefined,
    cashPrice: undefined,
  };
  setPriceRows([...priceRows, newRow]);
};

  const handleDeleteRow = (rowId:number) => {
    const updatedRows = priceRows.filter(row => row.id !== rowId);
    setPriceRows(updatedRows);
  };

  const handleChange = (value:number) => {
    setParentId(value)
    form.resetFields(['child_category']);
  };

  const steps = [
  {
    title: "基本信息",
    content: [
      <div style={{ height: "500px" }}>
        <h1
          style={{
            width: "200px",
            height: "50px",
            lineHeight: "50px",
            fontSize: "20px",
            fontWeight: "bold",
          }}
        >
          基本信息
        </h1>
        <Form
          {...formItemLayout}
          variant="filled"
          style={{ maxWidth: 600, margin: "auto" }}
          form={form}
        >
          <Form.Item
            label="商品名称"
            name="name"
            rules={[{ required: true, message: "请输入商品名称!" },
                  { max: 20, message: "商品名称不能超过20个字!" }
            ]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

            <Form.Item
              label="商品头图"
              name="imageUrl"
              rules={[{ required: true, message: "请上传商品头图!" }]}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                listType="picture-card"
                fileList={fileList}
                onChange={({ fileList }) => setFileList(fileList)}
                beforeUpload={() => false}
                onPreview={handlePreview}
                onRemove={handleRemove}
              >
                {fileList.length === 0 && (
                  <div>
                    <UploadOutlined />
                    <div style={{ marginTop: 8 }}>上传</div>
                  </div>
                )}
              </Upload>
            </Form.Item>

          <Form.Item
            label="商品描述"
            name="description"
            rules={[{ required: true, message: "请输入商品描述!" },
                   { max: 100, message: "文字描述不能超过100个字!" }]}
          >
            <Input.TextArea
              style={{ height: "200px" }}
              placeholder="请输入详细文字描述，不超过100字"
            />
          </Form.Item>

          <Form.Item
            label="商品类型"
            name="parent_category"
            rules={[{ required: true, message: "请选择商品类型!" }]}
          >
            <Select placeholder="请选择" style={{ textAlign: "left" }}  
            onChange={(value)=>handleChange(value)}>
              {parentCategoryOption}
            </Select>
          </Form.Item>

          <Form.Item
            label="商品分类"
            name="child_category"
            rules={[{ required: true, message: "请选择商品分类!" }]}
          >
            <Select placeholder="请选择" style={{ textAlign: "left" }}  >
              {childCategoryOption(parentId)}
            </Select>
          </Form.Item>
        </Form>
      </div>,
    ],
  },
  {
    title: "服务保障",
    content: [
      <div style={{ height: "500px" }}>
        <h1
          style={{
            width: "200px",
            height: "50px",
            lineHeight: "50px",
            fontSize: "20px",
            fontWeight: "bold",
          }}
        >
          服务保障
        </h1>
        <Form
          {...formItemLayout}
          variant="filled"
          style={{ maxWidth: 600, margin: "auto" }}
          form={form}
        >
          <Form.Item
            label="供应商名称"
            name="vendor"
            rules={[{ required: true, message: "请输入供应商名称!" },
            { max: 20, message: "供应商名称不能超过20个字!" }
          ]}
          >
            <Input placeholder="请输入供应商名称" />
          </Form.Item>

          <Form.Item
            label="供应商联系方式"
            name="wendorPhone"
            rules={[{ required: true, message: " 请输入供应商电话!" },
            {pattern: /^1[3-9]\d{9}$/, message: '请输入11位手机号!' },]}
          >
            <Input placeholder="请输入供应商电话" />
          </Form.Item>
          <Form.Item
            label="服务保障"
            name="serviceGuarante"
            rules={[{ required: true, message: "请输入服务保障!" },
            { max: 100, message: "服务保障不能超过100个字!" }
          ]}
          >
            <Input.TextArea
              style={{ height: "200px" }}
              placeholder="请输入服务保障"
            />
          </Form.Item>
        </Form>
      </div>,
    ],
  },
  {
    title: "支付方式",
    content: [
      <div style={{ height: "500px" }}>
        <h1
          style={{
            width: "200px",
            height: "50px",
            lineHeight: "50px",
            fontSize: "20px",
            fontWeight: "bold",
          }}
        >
          支付方式
        </h1>
            <Form 
           form={form}
            {...formItemLayout}
            variant="filled"
            style={{width:'900px',height:'500px',margin:"auto",maxHeight: "450px", overflowY: "auto",lineHeight:'0px'}}>
          {priceRows.map((row,index) => (
            <div key={row.id} 
            style={{ maxWidth: 900 ,display:'flex',alignContent:'center',justifyContent:"space-between", marginBottom: "20px"}}
            >
            <Form.Item
              label="价格类型"
              name={`payTypes${row.id}`}
              rules={[{ required: true, message: "请选择价格类型!" }]}
              style={{ width: "300px" }}
            >
              <Select
                placeholder="请选择"
                style={{ textAlign: "left", width: "200px" }}
              >
                {payOption}
              </Select>
            </Form.Item>
            <Form.Item
              label="积分数量"
              name={`pointPrice${row.id}`}
              rules={[{ required: true, message: "请输入积分数量!" },
              {pattern: /^[1-9]\d*$/, 
              message: '积分数量为正整数!'
              }]}
              style={{ width: "300px" }}
            >
              <Input placeholder="请输入" style={{ width: "200px" }} />
            </Form.Item>
            <Form.Item
              label="现金价格"
              name={`cashPrice${row.id}`}
              rules={[{ required: true, message: "请输入现金价格!" },
              { pattern: /^(0|[1-9][0-9]*)(\.\d{1,2})?$/, 
                message: '请输入正确的现金价格，最多保留两位小数!'
                }]
              }
              style={{ width: "300px",whiteSpace: 'nowrap'}}
            >
              <Input placeholder="请输入" style={{width:'200px'}}/>
            </Form.Item>      
          <Button
              type="primary"
              onClick={() => handleDeleteRow(row.id)}
              style={{marginLeft:'10px'}}
            >
              删除
            </Button>
          </div> ))}
            <Button type="dashed"  style={{ width: "100%",marginTop:'10px'}} onClick={handleAddRow} >
              + 添加价格类型
            </Button>
        </Form>
      </div>,
    ],
  },
  {
    title: "其他",
    content: [
      <div style={{ height: "500px" }}>
        <h1
          style={{
            width: "200px",
            height: "50px",
            lineHeight: "50px",
            fontSize: "20px",
            fontWeight: "bold",
          }}
        >
          其他
        </h1>
        <Form
          form={form}
          {...formItemLayout}
          variant="filled"
          style={{ maxWidth: 600, margin: "auto" }}
        >
          <Form.Item label="不发货地区" name="blackCity">
            <Select placeholder="请选择" style={{ textAlign: "left" }}>
              {provinceOption}
            </Select>
          </Form.Item>
          <Form.Item label="兑换上限" name="兑换上限">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="库存" name="库存"  rules={[{ required: true, message: "请输入库存数量!" },
              {pattern: /^[1-9]\d*$/, 
              message: '库存数量为正整数!'
              }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="上线时间"
            name="onlineTime"
            rules={[{ required: true, message: "请选择上线时间!" }]}
          >
            <DatePicker placeholder="请选择" style={{ width: "350px" }} />
          </Form.Item>
          <Form.Item
            label="下线时间"
            name="offlineTime"
            rules={[{ required: true, message: "请选择下线时间!" }]}
          >
            <DatePicker placeholder="请选择" style={{ width: "350px" }} />
          </Form.Item>
          <Form.Item
            label="投放地区"
            name="whiteCity"
            rules={[{ required: true, message: "请选择投放城市!" }]}
          >
            <Select placeholder="请选择" style={{ textAlign: "left" }}>
              {provinceOption}
            </Select>
          </Form.Item>
        </Form>
      </div>,
    ],
  },
];
  
  const { token } = theme.useToken();
  const [current, setCurrent] = useState(0);

  const next =async() => {
    try {
      await form.validateFields();
      setCurrent(current + 1);
    } catch (errorInfo) {
      console.log("Validation failed:", errorInfo);
    }
  };

  const prev = () => {
    setCurrent(current - 1);
  };

  const items = steps.map((item) => ({ key: item.title, title: item.title }));

  const contentStyle: React.CSSProperties = {
    lineHeight: "260px",
    textAlign: "center",
    color: token.colorTextTertiary,
    backgroundColor: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: `1px dashed ${token.colorBorder}`,
    marginTop: 16,
  };

    const handleReset = () => {
    form.resetFields();
  };


  return (
    <div style={{paddingLeft:30,paddingRight:30,paddingTop:10}}>
      <Steps current={current} items={items} />
      <div style={contentStyle}>{steps[current].content}</div>
      <div style={{ marginTop: 24 }}>
        <Button type="primary" style={{ margin: "0 8px" }} >
          暂存
        </Button>
        <Button type="primary" style={{ margin: "0 8px" }} onClick={handleReset}>
          重置
        </Button>
        {current < steps.length - 1 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === steps.length - 1 && (
          <Button type="primary" onClick={() => message.success("创建成功!")}>
            提交
          </Button>
        )}
        {current > 0 && (
          <Button style={{ margin: "0 8px" }} onClick={() => prev()}>
            上一步
          </Button>
        )}
      </div>
    </div>
  );
}

export default AddProduct;
